package com.lwj.liwanjia.view.activity.indent;


import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.lwj.liwanjia.R;
import com.lwj.liwanjia.adapter.GwcIndentAdapter;
import com.lwj.liwanjia.base.BaseActivity;
import com.lwj.liwanjia.base.MyApplication;
import com.lwj.liwanjia.bean.AddressBean;
import com.lwj.liwanjia.bean.AlipayBean;
import com.lwj.liwanjia.bean.JieSuanBean;
import com.lwj.liwanjia.bean.PwdBean;
import com.lwj.liwanjia.bean.WxBean;
import com.lwj.liwanjia.bean.YikaTongPayBean;
import com.lwj.liwanjia.impl.AlipayView;
import com.lwj.liwanjia.impl.IsSetPwdView;
import com.lwj.liwanjia.impl.WxView;
import com.lwj.liwanjia.impl.YikatongPayView;
import com.lwj.liwanjia.presenter.AlipayPresenter;
import com.lwj.liwanjia.presenter.IsSetPwdPresenter;
import com.lwj.liwanjia.presenter.WxPayPresenter;
import com.lwj.liwanjia.presenter.YktPayPresenter;
import com.lwj.liwanjia.utils.PayDialog;
import com.lwj.liwanjia.utils.PwdDialog;
import com.lwj.liwanjia.utils.RxBus;
import com.lwj.liwanjia.utils.SpfUtils;
import com.lwj.liwanjia.utils.ZfFangshiDialog;
import com.lwj.liwanjia.utils.ZfPwdDialog;
import com.lwj.liwanjia.view.activity.address.AddressActivity;
import com.lwj.liwanjia.view.activity.login.LoginActivity;
import com.lwj.liwanjia.view.activity.myindent.MyIndentActivity;
import com.superrecycleview.superlibrary.recycleview.SuperRecyclerView;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.modelpay.PayResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import constants.Constants;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

public class IndentActivity extends BaseActivity implements AlipayView, YikatongPayView, WxView, IsSetPwdView {

    @BindView(R.id.tv_left)
    TextView tvLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.rlv_indent)
    SuperRecyclerView rlvIndent;
    @BindView(R.id.tv_zongjia)
    TextView tvZongjia;
    @BindView(R.id.tv_pay)
    TextView tvPay;

    private GwcIndentAdapter adapter;
    private List<JieSuanBean.DataBean.ShopInfoBean> list = new ArrayList<>();
    private List<String> strList = new ArrayList<>();
    private AdressViewHolder adressHolder;
    private ZhifuViewHolder zhifuHolder;
    private JiesuanViewHolder jiesuanHolder;
    private ZfFangshiDialog zfFangshiDialog;//支付方式
    private PayDialog payDialog;
    private int checkPosition;//支付方式
    private String token;
    private JieSuanBean.DataBean dataBean;
    private String addressId;//地址ID
    private String fapiaoId;//发票ID
    private AlipayPresenter alipayPresenter;//支付宝支付
    private YktPayPresenter yktPayPresenter;//一卡通支付
    private WxPayPresenter wxPayPresenter;//微信支付
    private IsSetPwdPresenter isSetPwdPresenter;//判断是否设置了一卡通支付密码
    private Map<String, Object> map = new HashMap<>();
    private IWXAPI api;
    private Subscription subscribe;
    private PwdDialog pwdDialog;

    @Override
    protected void initView() {
        api = WXAPIFactory.createWXAPI(this, Constants.APP_ID);
        tvLeft.setVisibility(View.VISIBLE);
        tvTitle.setText("确认订单");
        dataBean = (JieSuanBean.DataBean) getIntent().getSerializableExtra("data");
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        rlvIndent.setLayoutManager(manager);
        rlvIndent.setRefreshEnabled(false);
        rlvIndent.setLoadMoreEnabled(false);
        adapter = new GwcIndentAdapter(this, list);
        addView();
        rlvIndent.setAdapter(adapter);
        token = SpfUtils.getSpfUtils(this).getToken();
        listener();
        JieSuanBean.DataBean.AddressBean address = dataBean.getAddress();
        if (!TextUtils.isEmpty(address.getAddress())) {
            adressHolder.detailAddress.setVisibility(View.VISIBLE);
            adressHolder.addAddress.setVisibility(View.GONE);
            adressHolder.tvName.setText(address.getName());
            adressHolder.tvAddress.setText(address.getAddress());
            adressHolder.tvPhone.setText(address.getPhone());
            addressId = address.getConsigneeId();
        } else {
            adressHolder.detailAddress.setVisibility(View.GONE);
            adressHolder.addAddress.setVisibility(View.VISIBLE);
        }
        jiesuanHolder.tvSum.setText(dataBean.getSum() + "");
        jiesuanHolder.tvShijiprice.setText("￥" + dataBean.getSumPrice());
        jiesuanHolder.tvZongjia.setText("￥" + dataBean.getSumPrice());
        tvZongjia.setText("￥" + dataBean.getSumPrice());
        alipayPresenter = new AlipayPresenter(this);
        yktPayPresenter = new YktPayPresenter(this);
        wxPayPresenter = new WxPayPresenter(this);
        isSetPwdPresenter = new IsSetPwdPresenter(this);
        subscribe = RxBus.getInstance().toObserverable(String.class).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<String>() {
            @Override
            public void call(String s) {
                if (s.equals("支付完成")) {
                    startActivity(new Intent(IndentActivity.this, PayCompleteActivity.class).putExtra("type", "1"));
                    finish();
                } else if (s.equals("支付取消") || s.equals("支付失败")) {
                    Intent intent = new Intent(IndentActivity.this, MyIndentActivity.class);
                    intent.putExtra("type", "-1");
                    startActivity(intent);
                    finish();
                }
            }
        });
    }

    private void listener() {

        //选择发票
        zhifuHolder.rlFapiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(IndentActivity.this, FaPiaoActivity.class);
                intent.putExtra("price", "￥" + dataBean.getSumPrice());
                startActivityForResult(intent, 2);
            }
        });

//        //选择支付方式
//        zhifuHolder.rlZhifufangshi.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                zfFangshiDialog = new ZfFangshiDialog(IndentActivity.this);
//                zfFangshiDialog.show();
//                //点击确认
//                zfFangshiDialog.getQueRen().setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        int section = zfFangshiDialog.getSection();
//                        if (section == 0) {
//                            zhifuHolder.tvZhifufangshi1.setText("在线支付");
//                        } else if (section == 1) {
//                            zhifuHolder.tvZhifufangshi1.setText("货到付款");
//                        }
//                        zfFangshiDialog.dismiss();
//                    }
//                });
//            }
//        });
        //留言
        zhifuHolder.etLiuyan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                zhifuHolder.etLiuyan.setFocusable(true);
                zhifuHolder.etLiuyan.setFocusableInTouchMode(true);
                zhifuHolder.etLiuyan.requestFocus();
                InputMethodManager inputManager = (InputMethodManager) zhifuHolder.etLiuyan.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.showSoftInput(zhifuHolder.etLiuyan, 0);
            }
        });
        //地址修改
        adressHolder.detailAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(IndentActivity.this, AddressActivity.class);
                intent.putExtra("type", "订单");
                startActivityForResult(intent, 1);
            }
        });
        //地址新增
        adressHolder.addAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(IndentActivity.this, AddressActivity.class);
                intent.putExtra("type", "订单");
                startActivityForResult(intent, 3);
            }
        });
    }

    private void addView() {
        //选择配送地址和客户信息
        View adressView = LayoutInflater.from(this).inflate(R.layout.indent_address_layout, null);
        adressHolder = new AdressViewHolder(adressView);
        adapter.addHeaderView(adressView);
        //总的商品价格信息
        View jiesuanView = LayoutInflater.from(this).inflate(R.layout.indent_jiesuan_layout, null);
        jiesuanHolder = new JiesuanViewHolder(jiesuanView);
        adapter.addFooterView(jiesuanView);
        //选择支付方式，配送方式，发票
        View zhifuView = LayoutInflater.from(this).inflate(R.layout.indent_layout, null);
        zhifuHolder = new ZhifuViewHolder(zhifuView);
        adapter.addFooterView(zhifuView);
    }

    @Override
    protected void initData() {
        list.clear();
        list.addAll(dataBean.getShopInfo());
        adapter.notifyDataSetChanged();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_indent;
    }

    @OnClick({R.id.tv_left, R.id.tv_pay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_left://返回
                finish();
                break;
            case R.id.tv_pay://去付款
                if (addressId == null) {
                    Toast.makeText(this, "地址不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                payDialog = new PayDialog(this,dataBean.getSumPrice());
                payDialog.show();
                getMaps();
                //确认付款
                payDialog.getPay().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //选中了哪一种支付
                        checkPosition = payDialog.getCheckPosition();
                        if (checkPosition == 0) {//一卡通支付
                            isSetPwdPresenter.isSetPwd(token);
                        } else if (checkPosition == 1) {//支付宝支付
                            alipayPresenter.getAlipayInfo(map);
                        } else if (checkPosition == 2) {//微信支付
                            if (api.isWXAppInstalled()) {
                                wxPayPresenter.getWxPayInfo(map);
                            } else {
                                Toast.makeText(IndentActivity.this, "未安装微信", Toast.LENGTH_SHORT).show();
                            }
                        }
                        payDialog.dismiss();
                    }
                });
                break;
        }
    }

    private void getMaps() {
        map.put("token", token);
        map.put("consigneeId", addressId);
        if (zhifuHolder.tvFapiao1.getText().toString().equals("纸质发票") && fapiaoId != null) {
            map.put("liwanjiaInvoiceId", fapiaoId);
        }
        String liuyan = zhifuHolder.etLiuyan.getText().toString();
        if (!TextUtils.isEmpty(liuyan)) {
            map.put("payInfo", liuyan);
        }
        map.put("tradeId", dataBean.getOrderIds());
    }

    @Override
    public void showError(Exception e) {
        Toast.makeText(this, "支付有误", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void isSetPwd(PwdBean pwdBean) {
        if (pwdBean.getState() == 0) {
            Toast.makeText(this, "访问失败", Toast.LENGTH_SHORT).show();
        } else if (pwdBean.getState() == 1) {
            if (pwdBean.isData()) {//设置过支付密码
                pwdDialog = new PwdDialog(this);
                pwdDialog.show();
                pwdDialog.setOnFinishInput(new PwdDialog.OnPasswordInputFinish() {
                    @Override
                    public void inputFinish() {
                        map.put("payPassword", pwdDialog.getStrPassword());
                        yktPayPresenter.getYktpayInfo(map);
                    }
                });
            } else {
                ZfPwdDialog zfPwdDialog = new ZfPwdDialog(this);
                zfPwdDialog.show();
            }
        }
    }

    @Override
    public void getWxPayInfo(WxBean wxBean) {
        if (wxBean.getState() == 0) {
            Toast.makeText(this, "接口有误", Toast.LENGTH_SHORT).show();
        } else if (wxBean.getState() == 1) {
            WxBean.DataBean data = wxBean.getData();
            PayReq req = new PayReq();
            req.appId = data.getMsg().getAppid();
            req.partnerId = data.getMsg().getPartnerid();
            req.prepayId = data.getMsg().getPrepayid();
            req.nonceStr = data.getMsg().getNoncestr();
            req.timeStamp = String.valueOf(data.getMsg().getTimestamp());
            req.packageValue = data.getMsg().getPackageX();
            req.sign = data.getMsg().getSign();
            api.sendReq(req);
        }

    }

    @Override
    public void getYktpayInfor(YikaTongPayBean yikaTongPayBean) {
        if (yikaTongPayBean.getState() == 0) {
            Toast.makeText(this, "支付失败", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(IndentActivity.this, MyIndentActivity.class);
            intent.putExtra("type", "-1");
            startActivity(intent);
            finish();
        } else if (yikaTongPayBean.getState() == 1) {
            if (yikaTongPayBean.getData().isSuccess()) {
                Toast.makeText(IndentActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                startActivity(new Intent(IndentActivity.this, PayCompleteActivity.class).putExtra("type", "0"));
                finish();
                pwdDialog.dismiss();
            } else {
                Toast.makeText(this, "支付失败", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(IndentActivity.this, MyIndentActivity.class);
                intent.putExtra("type", "-1");
                startActivity(intent);
                finish();
            }
        } else if (yikaTongPayBean.getState() == 3) {//密码有误
            TextView[] tvList = pwdDialog.getTvList();
            for (TextView tv : tvList) {
                tv.setText("");
            }
            pwdDialog.getTvError().setVisibility(View.VISIBLE);
        } else if (yikaTongPayBean.getState() == 11) {
            Toast.makeText(this, "余额不足", Toast.LENGTH_SHORT).show();
            pwdDialog.dismiss();
        }
    }

    @Override
    public void getAlipayInfo(AlipayBean alipayBean) {
        if (alipayBean.getState() == 0) {
            Toast.makeText(this, "接口有误", Toast.LENGTH_SHORT).show();
        } else {
            final String orderInfo = alipayBean.getData().getAliAppPay();
            Runnable payRunnable = new Runnable() {

                @Override
                public void run() {
                    PayTask alipay = new PayTask(IndentActivity.this);
                    Map<String, String> result = alipay.payV2(orderInfo, true);
                    String resultStatus = result.get("resultStatus");
                    Message msg = new Message();
                    msg.what = 1;
                    msg.obj = resultStatus;
                    mHandler.sendMessage(msg);
                }
            };
            // 必须异步调用
            Thread payThread = new Thread(payRunnable);
            payThread.start();
        }
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                String resultStatus = (String) msg.obj;
                if (resultStatus.equals("9000")) {
                    Toast.makeText(IndentActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(IndentActivity.this, PayCompleteActivity.class).putExtra("type", "1"));
                    finish();
                } else if (resultStatus.equals("4000")) {
                    Toast.makeText(IndentActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(IndentActivity.this, MyIndentActivity.class);
                    intent.putExtra("type", "-1");
                    startActivity(intent);
                    finish();
                } else {
                    Toast.makeText(IndentActivity.this, "支付取消", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(IndentActivity.this, MyIndentActivity.class);
                    intent.putExtra("type", "-1");
                    startActivity(intent);
                    finish();
                }
            }
        }
    };

    static class AdressViewHolder {
        @BindView(R.id.tv_name)
        TextView tvName;
        @BindView(R.id.tv_phone)
        TextView tvPhone;
        @BindView(R.id.tv_address)
        TextView tvAddress;
        @BindView(R.id.detail_address)
        RelativeLayout detailAddress;//整个地址栏
        @BindView(R.id.tv_add_address)
        TextView addAddress;//添加地址

        AdressViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

    static class ZhifuViewHolder {
        @BindView(R.id.tv_zhifufangshi1)
        TextView tvZhifufangshi1;
        @BindView(R.id.rl_zhifufangshi)
        RelativeLayout rlZhifufangshi;
        @BindView(R.id.tv_fapiao1)
        TextView tvFapiao1;
        @BindView(R.id.rl_fapiao)
        RelativeLayout rlFapiao;
        @BindView(R.id.et_liuyan)
        EditText etLiuyan;

        ZhifuViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

    static class JiesuanViewHolder {
        @BindView(R.id.tv_peisongfei)
        TextView tvPeisongfei;//配送费
        @BindView(R.id.tv_youhui)
        TextView tvYouhui;//优惠
        @BindView(R.id.tv_shijiprice)
        TextView tvShijiprice;
        @BindView(R.id.tv_sum)
        TextView tvSum;
        @BindView(R.id.tv_zongjia)
        TextView tvZongjia;

        JiesuanViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

    /**
     * 发票
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 2) {//选择发票
                int type = data.getIntExtra("type", 0);
                if (type == 0) {
                    zhifuHolder.tvFapiao1.setText("电子发票");
                } else if (type == 1) {
                    zhifuHolder.tvFapiao1.setText("纸质发票");
                }
                fapiaoId = data.getStringExtra("liwanjiaInvoiceId");
            } else if (requestCode == 1) {//选择地址
                AddressBean.DataBean addressBean = (AddressBean.DataBean) data.getSerializableExtra("address");
                adressHolder.tvName.setText(addressBean.getConsigneeName());
                adressHolder.tvAddress.setText(addressBean.getConsigneeAddress());
                adressHolder.tvPhone.setText(addressBean.getConsigneePhone());
                addressId = addressBean.getCondigneeId();
            } else if (requestCode == 3) {
                adressHolder.detailAddress.setVisibility(View.VISIBLE);
                adressHolder.addAddress.setVisibility(View.GONE);
                AddressBean.DataBean addressBean = (AddressBean.DataBean) data.getSerializableExtra("address");
                adressHolder.tvName.setText(addressBean.getConsigneeName());
                adressHolder.tvAddress.setText(addressBean.getConsigneeAddress());
                adressHolder.tvPhone.setText(addressBean.getConsigneePhone());
                addressId = addressBean.getCondigneeId();
            }
        }
    }

    @Override
    protected void onDestroy() {
        if (alipayPresenter != null) {
            alipayPresenter = null;
        }
        if (yktPayPresenter != null) {
            yktPayPresenter = null;
        }
        if (wxPayPresenter != null) {
            wxPayPresenter = null;
        }
        if (!subscribe.isUnsubscribed()) {
            subscribe.unsubscribe();
        }
        if (isSetPwdPresenter != null) {
            isSetPwdPresenter = null;
        }
        super.onDestroy();
    }
}

